from threading import Thread

from app.controllers.response.response import SuccessResult
from app.database import convert
from app.models.po.hanfan.hanfan_new_predict_po import HanfanNewPredictPO
from app.models.po.luzha.luzha_predict_po import LuzhaPredictPO
from app.services.business.gaolu_diagnose.ind.abstract_ind import AbstractInd
from app.services.dal import base_dao
from app.utils import date_util
from app.utils.thread import CountDownLatch
from app.services.business.gaolu_diagnose.ind import ind_cls_dict
from app.exts import mysql_pool
from app.exts import influxdb
from datetime import datetime, timedelta
import logging as log
import json
from app.services.models.hanfan_model_v2 import hanfan_v_model
from app.services.models.luzha_model_v2 import luzha_mg_al_model, luzha_r_model, luzha_tio2_model


def get_luzha_data(start, end) -> list:
    records = convert.query(LuzhaPredictPO,
                            LuzhaPredictPO.DATE_TIME >= start,
                            LuzhaPredictPO.DATE_TIME <= end).all()
    return records


def dump_luzha_data():
    """
    查询并存储炉渣预测所需要的数据
    :return:
    """

    class SubThread(Thread):
        def __init__(self, name, latch, params):
            Thread.__init__(self)
            self.name = name
            self.latch = latch
            self.params = params
            self.result = 0

        def run(self):
            influxdb_client = influxdb.get_client()
            name = self.name
            params = self.params
            if name in ind_cls_dict.keys():
                try:
                    cls = ind_cls_dict[name]
                    instance: AbstractInd = cls(influxdb_client, params, mysql_pool)
                    value = instance.get_result()
                    self.result = value
                except Exception as e:
                    log.error("fail to get result of {}. {}".format(name, e), exc_info=1)
            self.latch.countDown()

    latch = CountDownLatch(len(key_words))

    date_start = date_util.dt_to_str(date_util.get_start_of_day(datetime.now() - timedelta(days=1)), '%Y-%m-%d')
    dt_start_tz = date_util.dt_to_str(date_util.get_start_of_day(datetime.now()) - timedelta(hours=16),
                                      '%Y-%m-%dT%H:%M:%SZ')
    dt_end_tz = date_util.dt_to_str(date_util.get_start_of_day(datetime.now()) + timedelta(hours=8),
                                    '%Y-%m-%dT%H:%M:%SZ')
    dt_start_hour_tz = date_util.dt_to_str(date_util.get_start_of_hour(datetime.now()) + timedelta(hours=8),
                                           '%Y-%m-%dT%H:%M:%SZ')
    dt_next_hour_tz = date_util.dt_to_str(date_util.get_next_of_hour(datetime.now()) + timedelta(hours=8),
                                          '%Y-%m-%dT%H:%M:%SZ')

    params = dict(dt_start=date_start,
                  dt_start_tz=dt_start_tz,
                  dt_end_tz=dt_end_tz,
                  dt_start_hour_tz=dt_start_hour_tz,
                  dt_next_hour_tz=dt_next_hour_tz
                  )

    thread_list = []
    for key in key_words:
        thread = SubThread(key, latch, params)
        thread.start()
        thread_list.append(thread)
    #
    latch.await()
    input = {thread.name: thread.result for thread in thread_list}

    mg_al_predict = luzha_mg_al_model.process(input)
    r_predict = luzha_r_model.process(input)
    tio2_predict = luzha_tio2_model.process(input)

    v = hanfan_v_model.process(input)

    luzha_predict = LuzhaPredictPO()
    luzha_predict.GMT_CREATE = datetime.now()
    luzha_predict.DATE_TIME = date_util.get_start_of_hour(datetime.now())
    luzha_predict.CG_LT_GL_GL04_Zha_Mg_Al = input['CG_LT_GL_GL04_Zha_Mg_Al']
    luzha_predict.CG_LT_GL_GL04_Zha_Mg_Al_PREDICT = mg_al_predict

    luzha_predict.CG_LT_GL_GL04_Zha_R = input['CG_LT_GL_GL04_Zha_R']
    luzha_predict.CG_LT_GL_GL04_Zha_R_PREDICT = r_predict

    luzha_predict.CG_LT_GL_GL04_Zha_TiO2 = input['CG_LT_GL_GL04_Zha_TiO2']
    luzha_predict.CG_LT_GL_GL04_Zha_TiO2_PREDICT = tio2_predict

    update_count = base_dao.save_or_update(LuzhaPredictPO,
                                           luzha_predict,
                                           LuzhaPredictPO.DATE_TIME == luzha_predict.DATE_TIME)

    hanfan_new = HanfanNewPredictPO()
    hanfan_new.GMT_CREATE = datetime.now()
    hanfan_new.DATE_TIME = date_util.get_start_of_hour(datetime.now())
    hanfan_new.CG_LT_GL_GL04_Tie_V_PREDICT = v
    hanfan_new.flag = 0
    # hanfan_new.CG_LT_GL_GL04_Tie_V = input['CG_LT_GL_GL04_Tie_V']
    # hanfan_new.CG_LT_GL_GL04_Vshoude = input['CG_LT_GL_GL04_Vshoude']
    columns = [key for key in HanfanNewPredictPO.__dict__.keys() if key.startswith("CG")]
    for column in columns:
        if column in input.keys():
            hanfan_new.__setattr__(column,input.get(column))

    record: HanfanNewPredictPO = convert.query(HanfanNewPredictPO,
                                               HanfanNewPredictPO.DATE_TIME == hanfan_new.DATE_TIME).first()
    if record:
        if record.flag == 0:
            count = convert.update_model(record, hanfan_new.__dict__)
    else:
        count = convert.add_one(hanfan_new)

    input['mg_al_predict'] = mg_al_predict
    input['r_predict'] = r_predict
    input['tio2_predict'] = tio2_predict
    input['v'] = v

    return input


key_words = [
    'CG_LT_GL_GL04_Tie_V',
    'CG_LT_GL_GL04_Tie_Ni',
    'CG_LT_GL_GL04_Tie_Cr',
    'CG_LT_GL_GL04_Zha_Al2O3',
    'CG_LT_GL_GL04_LDWDBTE1130_XB_Zhong5963',
    'CG_LT_GL_GL04_LJWDBTE1101_Zhong_4000',
    'CG_LT_GL_GL04_LDWDBTE1116_Zhong_Zhongxin5963',
    'CG_LT_GL_GL04_LDWDBTE1138_D_Wai6693',
    'CG_LT_GL_GL04_Zha_Mg_Al',
    'CG_LT_GL_GL04_Coke_Greater40mm',
    'CG_LT_GL_GL04_LDWDBTE1113_D_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1110_DB_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1135_DB_Wai6693',
    'CG_LT_GL_GL04_LDWDBTE1117_DN_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1103_DB_5160',
    'CG_LT_GL_GL04_LDWDBTE1107_B_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1108_B_Zhong5963',
    'CG_LT_GL_GL04_LDWDBTE1115_D_Nei5963',
    'CG_LT_GL_GL04_LDWDBTE1119_DN_Nei5963',
    'CG_LT_GL_GL04_LDWDBTE1112_DB_Nei5963',
    'CG_LT_GL_GL04_LDWDBTE1109_B_Nei5963',
    'CG_LT_GL_GL04_LDWDBTE1121_N_Zhong5963',
    'CG_LT_GL_GL04_LDWDBTE1102_Zhong_5160',
    'CG_LT_GL_GL04_LDWDBTE1111_DB_Zhong5963',
    'CG_LT_GL_GL04_LDWDBTE1141_Zhong_Zhongxin6693',
    'CG_LT_GL_GL04_LDWDBTE1137_DB_Nei6693',
    'CG_LT_GL_GL04_LDWDBTE1140_D_Nei6693',
    'CG_LT_GL_GL04_LDWDBTE1130_XB_Zhong5963',
    'CG_LT_GL_GL04_LDWDBTE1134_B_Nei6693',
    'CG_LT_GL_GL04_LDWDBTE1136_DB_Zhong6693',
    'CG_LT_GL_GL04_LDWDBTE1117_DN_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1139_D_Zhong6693',
    'CG_LT_GL_GL04_LDWDBTE1125_XN_Nei5963',
    'CG_LT_GL_GL04_Zha_R',
    'CG_LT_GL_GL04_Zha_TiO2',
    'CG_LT_GL_GL04_Zha_V2O5',
    'CG_LT_GL_GL04_Zha_SiO2',
    'CG_LT_GL_GL04_Zha_MgO',
    'CG_LT_GL_GL04_Zha_CaO',
    'CG_LT_GL_GL04_Zha_TiO2_1',
    'CG_LT_GL_GL04_Zha_R_1',
    'CG_LT_GL_GL04_Zha_Mg_Al_1',
    'CG_LT_GL_GL04_Tie_V_1',
    'CG_LT_GL_GL04_LDWDBTE1138_D_Wai6693',
    'CG_LT_GL_GL04_LDWDBTE1129_XB_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1120_N_Wai5963',
    'CG_LT_GL_GL04_LDWDBTE1128_X_Nei5963',
    'CG_LT_GL_GL04_LDWDBTE1135_DB_Wai6693',
    'CG_LT_GL_GL04_LDWDBTE1125_XN_Nei5963',
    'CG_LT_GL_GL04_LDWDBTE1154_XB_Wai6693',
    'CG_LT_GL_GL04_LDWDBTE1133_B_Zhong6693',
    'CG_LT_GL_GL04_Vshoude',
    'CG_LT_GL_GL04_CO2ZXFX',
    'CG_LT_GL_GL04_COZXFX',
    'CG_LT_GL_GL04_DWPJ',
    'CG_LT_GL_GL04_FCoalRate',
    'CG_LT_GL_GL04_FCokeRate',
    'CG_LT_GL_GL04_FLiLunTie',
    'CG_LT_GL_GL04_FSSJ',
    'CG_LT_GL_GL04_Ftswd',
    'CG_LT_GL_GL04_FYLL',
    'CG_LT_GL_GL04_FZWD',
    'CG_LT_GL_GL04_GFDNKG',
    'CG_LT_GL_GL04_GLRSZLL',
    'CG_LT_GL_GL04_LDYL',
    'CG_LT_GL_GL04_MQLYL',
    'CG_LT_GL_GL04_qiutuanZB',
    'CG_LT_GL_GL04_QLYC',
    'CG_LT_GL_GL04_RFH',
    'CG_LT_GL_GL04_RFWD',
    'CG_LT_GL_GL04_SBYCPJ',
    'CG_LT_GL_GL04_SBYCZB',
    'CG_LT_GL_GL04_shaojiekZB',
    'CG_LT_GL_GL04_TQXZS',
    'CG_LT_GL_GL04_XBYCPJ',
    'CG_LT_GL_GL04_XBYCZB',
    'CG_LT_GL_GL04_XFZDWPJ',
    'CG_LT_GL_GL04_LFLL',
    'CG_LT_GL_GL04_Yuanranliao_Ore_V2O5',
    'CG_LT_GL_GL04_RLB',
    'CG_LT_GL_GL04_FYL02',
    'CG_LT_GL_GL04_LLRSWD'
]

if __name__ == "__main__":
    r = SuccessResult(detail=dict(a=2))
    dump_luzha_data()
